import axios from "axios";
import { showNotify } from 'vant';
import router from "@/router/index.js";

const request = axios.create({
    baseURL: 'http://192.168.2.104:9999',
    timeout: 30000
});

// 请求拦截器
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json; charset=utf-8';
    let user = JSON.parse(localStorage.getItem('code_user') || '{}');
    config.headers['token'] = user.token;
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(response => {
    let res = response.data;
    if (typeof res === 'string') {
        try {
            res = JSON.parse(res);
        } catch (e) {
            // ignore
        }
    }

    if (res.code === '401') {
        showNotify({ type: 'danger', message: '登录已过期，请重新登录' });
        router.push('/login');
    }

    return res;
}, error => {
    if (error.response?.status === 404) {
        showNotify({ type: 'danger', message: '未找到请求接口' });
    } else if (error.response?.status === 500) {
        console.error(error);
        showNotify({ type: 'danger', message: '系统异常，请查看后端日志' });
    } else {
        console.error(error.message);
    }

    return Promise.reject(error);
});

export default request;
